Skip to content

fix(ssh): replay an undelivered remote PTY stop on the next handshake (#12447 item 1) - #17011

Merged
nwparker merged 3 commits into
mainfrom
fix/ssh-replay-undelivered-pty-kill
Aug 28, 2026
Merged

nwparker merged 3 commits into
mainfrom
fix/ssh-replay-undelivered-pty-kill

Conversation

@nwparker

@nwparker nwparker commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1210 $\color{#cf222e}{\Huge{\mathbf{−}}}$​23 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1187
Prod 16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​785 $\color{#cf222e}{\Huge{\mathbf{−}}}$​92 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​693

Fixes the remote process leak behind #12447 — the one its "Expected behavior" bullet 1 asks for: "if the remote kill cannot be delivered, record the intent and retry on reconnect — never silently drop it."

ELI5

You close a terminal that is running on a computer somewhere else. Orca sends "please stop" over the network. If the network hiccups at that exact moment, the message never arrives — and until now, Orca just shrugged and forgot about it. Your window closed, so it looked fine. But the program kept running on the other computer, forever, holding a shell and often a whole AI agent.

Now Orca writes the request down in a notebook that survives closing your laptop. Next time it talks to that same computer, it reads the notebook and asks again.

The tricky part is making sure it asks about the right thing. The remote side names its terminals pty-1, pty-2, … and starts over at pty-1 whenever it restarts. So "please stop pty-1" written down yesterday could hit a completely different terminal today — someone else's work. To prevent that, Orca also writes down a fingerprint the remote side gives each terminal when it is born. Before asking again, it checks the fingerprint still matches. If it doesn't, Orca tears the page out instead of asking.


Root cause

src/main/ipc/pty/runtime/kill.ts returned false when the shutdown RPC rejected with anything that was not isPtyAlreadyGoneError. It marked liveness unverifiable and warned — correct per docs/reference/ssh-execution-boundary.md, a transport failure observes nothing — and then nothing ever retried. There was no pending-kill journal.

A relay PTY is a child of the detached relay daemon, not of the ssh channel, and the shipped grace default is keep alive until reset. So the shell — and whatever agent it was running — survived on the user's remote machine indefinitely.

The same hole existed on the offline close: when no provider is registered, killPtyFromRuntimeController tombstones the lease terminated locally and tells the renderer, but the relay is never asked at all. That branch is the common one — a laptop closed mid-failure.

#16752 (client-local close tombstones) and #16970 (relay-id fence) stopped the client showing or resurrecting a tab for that orphan. Neither one stopped the process.

The fix

Record the intent durably, on both kill routes. There are two: killPtyFromRuntimeController (runtime/CLI) and the pty:kill IPC, which is what window.api.pty.kill reaches and therefore what an ordinary tab close uses — the route #12447 actually describes. They are separate implementations and both now record. The IPC handler moved out of ipc/inspect.ts into ipc/renderer-kill.ts: it was not what that file is named for, and keeping it there put the file over the 300-line budget (no max-lines disable was added).

The record itself: SshRemotePtyLease — the existing per-(targetId, relayPtyId) durable record, which already survives restart — gains one optional field, pendingKill. No parallel journal: the lease is already the thing that names a remote PTY, so the eventual liveness consolidation adopts one record rather than deleting a second one. src/shared/ssh-pending-pty-kill.ts holds the colocated type plus the pure decision logic, deliberately shaped after src/shared/closed-terminal-tab-tombstones.ts (TTL + cap + a retirement rule that never deletes on absence of evidence).

Replay it on the next handshake to the same host. replayPendingSshPtyKills runs at the top of SshRelaySession.reattachKnownPtys, which both establish() and reconnect() await — so a PTY that dies here is never re-adopted as a live pane by the reattach that follows it.

Fence it on the host-minted PTY incarnation. toAppSshPtyId is connectionId + relayPtyId, and a redeployed relay renumbers from pty-1 (src/relay/pty-handler.ts, private nextId = 1), so the id alone is not safe — that is the #16970 collision. The relay mints an incarnationId (randomUUID()) per PTY process and already publishes it on pty.listProcesses. The replay only issues pty.shutdown when the host still reports that exact incarnation for that id, and it re-checks that immediately before each call rather than trusting the selection pass.

This fence has to live on the client. pty.shutdown takes { id, immediate, keepHistory } and no identity parameter, and the relay kills whatever holds the id — its handler also returns the same empty success for a PTY it never had. Adding an expectedIncarnation param would be a safe Rule-1 field, but an old host would ignore it, so the client would still have to fence itself and the host change would buy nothing today.

Retire on three paths, and never assert an exit.

Trigger Action
Shutdown delivered, and a fresh inventory no longer lists the id clear the intent, mark the lease terminated
Host answers and does not list the id clear the intent, mark the lease terminated
TTL (30d) a durable prune deletes the order; the lease is untouched
Relay id recycled onto a different incarnation clear the intent, mark the lease expired — no kill
Anything else (transport failure, no inventory, host publishes no incarnation) keep the intent; the next handshake asks again

Only the two rows carrying positive evidence of absence from the host that owns the process write a terminated tombstone, and both derive it from a successful pty.listProcesses — never from an error predicate. isPtyAlreadyGoneError matches message text (/Session not found/i) that a transport failure could wear, and #16763 landed precisely because that class of flattening had already gone wrong here once; a tombstone resting on it would bury a live remote shell. Nothing here emits a renderer exit event — the synthetic exit already fired at kill time — and no branch invents an exited for something nobody observed. The vocabulary stays live / unverifiable / exited.

Retirement is never inferred from a resolved RPC. finishPtyShutdown deliberately does not clear the order. It runs both on paths that asked the host and on paths that never did, so retiring from there would be a contract every call site had to remember — and the one that forgot would silently drop a valid kill order. It is also not evidence: the relay answers pty.shutdown for a PTY it never had with the same empty success. Retirement belongs to the replay, which only ever acts on a live pty.listProcesses.

A recycled id expires the lease that named it. Declining to kill is only half the fix. The reattach one step later filters on lease state and fences on paneKey/tabId, never on incarnation — so an untouched lease would bind the user's old pane to whatever process now holds the recycled id. It is marked expired, not terminated: losing the route is all that was observed, and nothing says the shell it named ever died.

Only a caller that gives the PTY up for good records an order. This is the sharpest edge in the change and it is worth stating explicitly. stopAndWaitPtyFromRuntimeController deliberately records nothing: worktree sleep stops through it and wraps those stops in markReversibleStops, and when one does not land the pane is left live and usable and the failure is handed back to the caller. An order recorded there would come back on a later handshake and kill a terminal the user had gone back to using — turning a leak fix into a data-loss bug. recordUndeliveredSshPtyKill additionally refuses any PTY a reversible stop currently owns, so the rule is enforced rather than assumed. Both are covered by tests.

Wire-compatibility analysis

Per docs/reference/remote-wire-compatibility.md:

  • No new RPC method and no new stream opcode. Rule 2 does not apply. The replay uses pty.listProcesses and pty.shutdown, both long-shipped.
  • No new field on any frame. pendingKill is client-local persisted state and never crosses the wire.
  • Reads one existing optional field. incarnationId on pty.listProcesses results (added in fix(terminal): make remote agent sessions host-authoritative #9687). That is Rule 1, and it has the second state Rule 1 alone does not describe: absent means the host never published one — not "no incarnation", and not "matches". decideSshPendingPtyKill returns defer for absent, so a client newer than its host does not replay at all rather than replaying unfenced. Degraded, never dangerous. The record also cannot be created without an incarnation (recordUndeliveredSshPtyKill no-ops), so against a host that never publishes one the whole feature is inert and behavior is exactly today's.
  • Rule 3 (what the host publishes). Nothing changes about what the host publishes.
  • Old client, newer store. normalizeSshRemotePtyLease is a strict whitelist, so an older build reading a store written by this one drops pendingKill and behaves exactly as it does today. A downgrade loses queued kill orders; it cannot corrupt or misfire them. That whitelist is also why normalizeSshPendingPtyKill had to be added to it — without that the record was silently stripped on every launch, the same failure closed-terminal-tab-tombstones.ts records having shipped once. A test covers it.
  • The cross-version harness (tests/e2e/cross-version-wire/) covers the terminal stream only and is unaffected; this change is on the relay RPC path, which it does not exercise, and nothing about the framing moved.

Cost on the connect path, and containment

Zero when nothing is pending — replayPendingSshPtyKills reads the store and returns before touching the mux. When something is, it is one inventory per wave of 4 plus one to prove the batch: two round trips for the common single-order case, ceil(n/4)+1 at worst. A per-PTY verifyPtyStopped was the first shape and cost two round trips per order; one inventory for the whole batch was the second and left the fence going stale across the batch. Per-wave is the compromise, and it is what keeps a stop's identity evidence within one round trip of the stop.

replayPendingSshPtyKills never rejects. It is best-effort work that establish()/reconnect() await, so an unguarded throw — including from a persistence write — would turn a failed cleanup into a failed SSH connection, which is strictly worse than the leak. Two tests pin it, one for a throwing store read and one for a throwing write.

Growth is bounded by a 30d TTL and 200 records per target (not globally), enforced on write, on read, and by a durable prune that actually deletes.

Residual risks, stated rather than implied

  • The fence is a large improvement, not a guarantee. pty.shutdown carries { id, immediate, keepHistory } and no incarnation, so the host enforces nothing and no client-side arrangement can make list-then-kill atomic. Re-reading per wave and re-checking beside each call narrows the window to one round trip; it cannot close it. Closing it needs the host to refuse a stale kill — an incarnation on pty.shutdown, capability-negotiated per Rule 2. That is deliberately out of scope here and is exactly the kind of thing the SSH-v3 consolidation should absorb: "the execution host owns everything that touches execution."
  • Old relays that never publish incarnationId. Their orders defer forever and leave only via the 30d TTL, which deliberately does not tombstone the lease. That is correctness over leak-prevention — an unfenced kill on a renumbered id is worse than the leak — but it does mean the leak is unfixed against pre-fix(terminal): make remote agent sessions host-authoritative #9687 hosts.
  • The confirming inventory checks presence, not incarnation. If a kill ever did land on the wrong process, a third process reusing that id before the confirm read would be indistinguishable from "never died". It self-corrects on the next reconnect via relay-id-recycled, but nothing surfaces that a wrong kill may have happened. Diagnostics gap, not a correctness one.
  • confirmDelivered's inventory read is not shouldContinue()-gated mid-loop, so a late retirement can land over a superseded mux. It only ever acts on positive host evidence, so this is redundant rather than wrong.

Deliberately not in this PR

finishPtyShutdown marks the lease terminated and calls markClaudePtyExited on RPC success alone, including on a branch whose own comment says the relay was never asked. By this PR's own standard that is unverifiable being written as exited. It is pre-existing, it is not compounded here — this change no longer touches that function's retirement behaviour at all, and the replay reads pendingKill across every lease state, so even a wrongly-tombstoned lease still gets its order replayed. Fixing it properly means settling what counts as proof of death across every finishPtyShutdown caller, which deserves its own review rather than riding along. Tracked as follow-up work.

Fix evidence

Every test was verified to bite by reverting the fix and capturing the red output.

1. The leak itself — remove the recordUndeliveredSshPtyKill calls from kill.ts:

 × records the stop when the shutdown RPC rejects with a transport failure 1007ms
 × records the stop when no provider is registered to deliver it 3ms
 FAIL  src/main/ipc/pty-ssh-undelivered-kill.test.ts > undelivered SSH stops > records the stop when the shutdown RPC rejects with a transport failure
 AssertionError: expected "vi.fn()" to be called at least once
 FAIL  src/main/ipc/pty-ssh-undelivered-kill.test.ts > undelivered SSH stops > records the stop when no provider is registered to deliver it
 AssertionError: expected "vi.fn()" to be called with arguments: [ 'ssh-1', 'pty-7', …(1) ]
 Number of calls: 0
      Tests  2 failed | 3 passed (5)

2. Restart survival — remove pendingKill from the lease load whitelist:

 × survives an app restart 35ms
 × records an intent for a PTY that has no lease row yet 13ms
 × caps pending kills per target so an unreachable host cannot grow the store 2534ms
 FAIL  src/main/persistence-ssh-pending-pty-kill.test.ts > Store SSH pending PTY kills > survives an app restart
 AssertionError: expected [] to deeply equal [ Array(1) ]
 - Expected
 + Received
 - [
 -   {
 -     "intent": {
 -       "attempts": 0,
 -       "incarnationId": "inc-a",
 -       "requestedAt": 1800000000000,
 -     },
 -     "ptyId": "pty-1",
 -   },
 - ]
 + []

3. The recycled-id fence — delete the incarnation-mismatch branch:

 × retires without killing when the relay id was recycled onto another PTY 3ms
 × refuses to kill a recycled relay id and retires the order instead 2ms
 FAIL  src/shared/ssh-pending-pty-kill.test.ts > decideSshPendingPtyKill > retires without killing when the relay id was recycled onto another PTY
 AssertionError: expected { action: 'replay' } to deeply equal { action: 'retire', …(1) }
 FAIL  src/main/ssh/ssh-pending-pty-kill-replay.test.ts > replayPendingSshPtyKills > refuses to kill a recycled relay id and retires the order instead
 AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
 Received:
 Number of calls: 1

The unfenced build kills the recycled PTY. That is the failure this test exists to prevent.

4. TTL retirement — delete the TTL branch:

 × retires past the TTL, ahead of every other branch 3ms
 × retires an order past its TTL without aiming it at whatever holds the id now 2ms
 FAIL  src/shared/ssh-pending-pty-kill.test.ts > decideSshPendingPtyKill > retires past the TTL, ahead of every other branch
 AssertionError: expected { action: 'replay' } to deeply equal { action: 'retire', reason: 'expired' }
 FAIL  src/main/ssh/ssh-pending-pty-kill-replay.test.ts > replayPendingSshPtyKills > retires an order past its TTL without aiming it at whatever holds the id now
 AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
 Number of calls: 1

5. Bounded growth — remove the per-target cap:

 × caps pending kills per target so an unreachable host cannot grow the store 2722ms
 FAIL  src/main/persistence-ssh-pending-pty-kill.test.ts > Store SSH pending PTY kills > caps pending kills per target so an unreachable host cannot grow the store
 AssertionError: expected [ { targetId: 'ssh-1', …(5) }, …(249) ] to have a length of 200 but got 250

6. The session wiring — remove the replayPendingSshPtyKills call from reattachKnownPtys:

 × replays a stop the client could not deliver, before reattach reads the leases 5ms
 FAIL  src/main/ssh/ssh-relay-session-pending-kill-replay.test.ts > SshRelaySession pending PTY kill replay > replays a stop the client could not deliver, before reattach reads the leases
 AssertionError: expected "vi.fn()" to be called with arguments: [ 'ssh:target-1@@pty-3', …(1) ]
 Number of calls: 0

7. The renderer kill route — remove the recordUndeliveredSshPtyKill calls from ipc/renderer-kill.ts (the pty:kill IPC a tab close reaches):

 × records the stop when the renderer pty:kill shutdown rejects 3ms
 × records the stop when renderer pty:kill finds no provider to deliver it 1ms
 FAIL  src/main/ipc/pty-ssh-undelivered-kill.test.ts > undelivered SSH stops > records the stop when the renderer pty:kill shutdown rejects
 AssertionError: expected "vi.fn()" to be called with arguments: [ 'ssh-1', 'pty-7', …(1) ]
 Number of calls: 0
 FAIL  src/main/ipc/pty-ssh-undelivered-kill.test.ts > undelivered SSH stops > records the stop when renderer pty:kill finds no provider to deliver it
 AssertionError: expected "vi.fn()" to be called with arguments: [ 'ssh-1', 'pty-7', …(1) ]
 Number of calls: 0
      Tests  2 failed | 8 passed (10)

8. The recycled-id lease expiry — delete the relay-id-recycled branch from retire(), leaving the order cleared but the lease active:

 × refuses to kill a recycled relay id and expires the lease that named it 3ms
 FAIL  src/main/ssh/ssh-pending-pty-kill-replay.test.ts > replayPendingSshPtyKills > refuses to kill a recycled relay id and expires the lease that named it
 AssertionError: expected [] to deeply equal [ 'pty-1' ]
      Tests  1 failed | 14 passed (15)

That is the state in which reattach binds the user's old pane to whatever now holds the recycled id.

9. The phantom lease's state — create the invented lease attached instead of terminated:

 × creates the missing lease terminated so reattach cannot adopt it 16ms
 AssertionError: expected 'attached' to be 'terminated' // Object.is equality
      Tests  1 failed | 10 passed (11)

10. The reversible-stop carve-out — re-add a recordUndeliveredSshPtyKill call to the stopAndWait failure path, and separately drop the reversibleStopOwnersByPtyId guard:

 × records nothing for a reversible stopAndWait that could not be delivered 3ms
 FAIL  src/main/ipc/pty-ssh-undelivered-kill.test.ts > undelivered SSH stops > records nothing for a reversible stopAndWait that could not be delivered
 AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
 Number of calls: 1
 × records nothing while a reversible stop owns the PTY 5ms
 AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
 Number of calls: 1

The other two retirement paths (delivery confirmed, host reports absent), the "still live after a replayed stop" case, the two-round-trip batching bound, and the wire-skew degradation are covered in src/main/ssh/ssh-pending-pty-kill-replay.test.ts.

Checks

  • pnpm tc clean
  • oxlint clean repo-wide; no max-lines disable added anywhere
  • Full unit suite: 64,240 tests passing, exit 0
  • pnpm test src/main/ipc/ src/main/ssh/ plus the persistence and shared suites — 465 files, 5137 passing

Churn outside the change itself: existing Store stubs in the PTY/SSH tests gained the new methods, and the pty:kill handler moved from ipc/inspect.ts to ipc/renderer-kill.ts (a straight lift, plus the recording calls).

A pty.shutdown that dies on the transport left the remote shell running
forever: kill.ts marked liveness unverifiable and nothing retried.

Record the undelivered stop on the existing durable SshRemotePtyLease and
replay it against the authoritative host on the next handshake to that same
target, fenced by the host-minted PTY incarnation so a replay cannot kill a
later PTY that reused a recycled pty-N id. Retire the record on confirmed
delivery, on the host reporting the PTY absent, and on a bounded TTL.

No wire change: the fence reads incarnationId, already published on
pty.listProcesses. A host that does not publish it degrades to no replay.
Worktree sleep stops through stopAndWait and marks those stops reversible;
when one does not land the pane stays live and the user keeps using it. An
order recorded there would come back on a later handshake and kill that
terminal. Only killPtyFromRuntimeController — where the client gives the PTY
up for good — records one, and it skips any PTY a reversible stop owns.
@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ebe4f84e-0b9f-4fb3-9657-209039653670

📥 Commits

Reviewing files that changed from the base of the PR and between 18217f4 and c0a0869.

📒 Files selected for processing (18)
  • src/main/ipc/pty-ssh-undelivered-kill.test.ts
  • src/main/ipc/pty/ipc/inspect.ts
  • src/main/ipc/pty/ipc/renderer-kill.ts
  • src/main/ipc/pty/provider/liveness.ts
  • src/main/ipc/pty/register-handlers.ts
  • src/main/ipc/pty/runtime/kill.ts
  • src/main/ipc/pty/runtime/undelivered-ssh-kill.ts
  • src/main/ipc/ssh-ipc-test-harness.ts
  • src/main/persistence-ssh-pending-pty-kill.test.ts
  • src/main/persistence/leasing-ssh-ptys/ssh-pty-kill-intent-operations.ts
  • src/main/persistence/loading-store/ssh-lease-recovery-operations.ts
  • src/main/ssh/ssh-pending-pty-kill-replay.test.ts
  • src/main/ssh/ssh-pending-pty-kill-replay.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/main/ssh/ssh-relay-session-terminal-error.test.ts
  • src/main/ssh/ssh-relay-session-test-fixtures.ts
  • src/shared/ssh-pending-pty-kill.test.ts
  • src/shared/ssh-pending-pty-kill.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

The change adds durable SSH PTY kill intents with incarnation identity, validation, TTL pruning, and per-target limits. Failed or unverifiable SSH shutdowns record intents when safe to replay. Persistence APIs manage recording, clearing, and replay-attempt counts. SSH session reattachment reads host inventory, replays matching intents, confirms shutdown results, and updates leases. Tests cover persistence, failure recording, decision logic, replay behavior, and session integration.

Merge Risk: 🟠 High · up to c0a08

Persisted SSH PTY stops can be replayed against a replacement remote process if the PTY ID is reused during the gap between identity validation and shutdown, potentially terminating unrelated user work. A separate timestamp issue can prevent newly recorded stops from replaying at all, so these merge-readiness risks require owner attention before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 40 functions across 30 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: replaying undelivered remote SSH PTY stops during the next handshake.
Description check ✅ Passed The description is comprehensive and on-topic. It explains the problem, implementation, safety rules, compatibility, risks, tests, and verification results. It does not reproduce several template head…
Full details: Description check

Explanation

The description is comprehensive and on-topic. It explains the problem, implementation, safety rules, compatibility, risks, tests, and verification results. It does not reproduce several template headings or explicitly provide the requested Visual Proof, AI Disclosure, Agent skill boundary, and checklist responses, but the core required information is present.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/main/ssh/ssh-relay-session-terminal-error.test.ts (1)

110-114: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse the shared createMockDeps fixture instead of local Store mock copies. src/main/ssh/ssh-relay-session-test-fixtures.ts already exports createMockDeps with the same mock Store, and this PR had to add the same four kill-intent mocks in three places. Each future Store method used by the relay session will need the same triple edit.

  • src/main/ssh/ssh-relay-session-terminal-error.test.ts#L110-L114: delete the local createMockDeps and import it from ./ssh-relay-session-test-fixtures.
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts#L163-L167: build the store in createSession from the shared fixture's mockStore, and keep only this file's specific overrides.

This follows the coding guideline: "Before writing new logic at any scale — a function, component, IPC channel, state store, or whole subsystem/flow — check whether an existing implementation already does the job (or nearly does). Extend or generalize it instead of building a parallel version".

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1e01391a-f4b0-47d6-a545-39dc3c254d02

📥 Commits

Reviewing files that changed from the base of the PR and between 65dd06a and 18217f4.

📒 Files selected for processing (28)
  • config/reliability-gates.jsonc
  • src/main/ipc/pty-controller-ownership-routing.test.ts
  • src/main/ipc/pty-daemon-controller-teardown.test.ts
  • src/main/ipc/pty-daemon-spawn-session-identity.test.ts
  • src/main/ipc/pty-daemon-ssh-lease-lifecycle.test.ts
  • src/main/ipc/pty-pane-reservation-settlement.test.ts
  • src/main/ipc/pty-runtime-ssh-binding-persistence.test.ts
  • src/main/ipc/pty-serializer-settlement-mapping.test.ts
  • src/main/ipc/pty-session-liveness-and-ownership.test.ts
  • src/main/ipc/pty-ssh-undelivered-kill.test.ts
  • src/main/ipc/pty/provider/liveness.ts
  • src/main/ipc/pty/runtime/kill.ts
  • src/main/ipc/pty/runtime/undelivered-ssh-kill.ts
  • src/main/ipc/ssh-ipc-test-harness.ts
  • src/main/persistence-ssh-pending-pty-kill.test.ts
  • src/main/persistence/leasing-ssh-ptys/ssh-normalization.ts
  • src/main/persistence/leasing-ssh-ptys/ssh-pty-kill-intent-operations.ts
  • src/main/persistence/loading-store/ssh-lease-recovery-operations.ts
  • src/main/ssh/ssh-pending-pty-kill-replay.test.ts
  • src/main/ssh/ssh-pending-pty-kill-replay.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/main/ssh/ssh-relay-session-pending-kill-replay.test.ts
  • src/main/ssh/ssh-relay-session-terminal-error.test.ts
  • src/main/ssh/ssh-relay-session-test-fixtures.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/shared/ssh-pending-pty-kill.test.ts
  • src/shared/ssh-pending-pty-kill.ts
  • src/shared/ssh-types.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

Comment on lines +110 to +113
getSshRemotePtyKillIntents: vi.fn().mockReturnValue([]),
recordSshRemotePtyKillIntent: vi.fn(),
clearSshRemotePtyKillIntent: vi.fn(),
noteSshRemotePtyKillReplayAttempt: vi.fn()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reset the new kill-intent mocks.

reset() leaves these mocks and configured intent results intact, so one test can affect a later test. Reset all four with the other mockStore methods.

Comment on lines +62 to +68
// Why keep the earliest requestedAt: the TTL bounds how long the intent may chase the host, and
// a repeated close must not extend it. Attempts carry over so replays stay countable.
existing.pendingKill = {
...intent,
requestedAt: Math.min(existing.pendingKill?.requestedAt ?? now, now),
attempts: existing.pendingKill?.attempts ?? intent.attempts
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Do not inherit an expired kill timestamp.

If a relay reuses this PTY ID after 30 days, this merge keeps the stale requestedAt, so the new undelivered kill is immediately excluded from replay. Treat an expired prior intent as absent before preserving its timestamp and attempts.

Proposed fix
+    const prior = existing.pendingKill
+    const priorIsCurrent =
+      prior &&
+      prior.requestedAt <= now &&
+      now - prior.requestedAt <= SSH_PENDING_PTY_KILL_TTL_MS
     existing.pendingKill = {
       ...intent,
-      requestedAt: Math.min(existing.pendingKill?.requestedAt ?? now, now),
-      attempts: existing.pendingKill?.attempts ?? intent.attempts
+      requestedAt: priorIsCurrent ? Math.min(prior.requestedAt, now) : now,
+      attempts: priorIsCurrent ? prior.attempts : intent.attempts
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Why keep the earliest requestedAt: the TTL bounds how long the intent may chase the host, and
// a repeated close must not extend it. Attempts carry over so replays stay countable.
existing.pendingKill = {
...intent,
requestedAt: Math.min(existing.pendingKill?.requestedAt ?? now, now),
attempts: existing.pendingKill?.attempts ?? intent.attempts
}
// Why keep the earliest requestedAt: the TTL bounds how long the intent may chase the host, and
// a repeated close must not extend it. Attempts carry over so replays stay countable.
const prior = existing.pendingKill
const priorIsCurrent =
prior &&
prior.requestedAt <= now &&
now - prior.requestedAt <= SSH_PENDING_PTY_KILL_TTL_MS
existing.pendingKill = {
...intent,
requestedAt: priorIsCurrent ? Math.min(prior.requestedAt, now) : now,
attempts: priorIsCurrent ? prior.attempts : intent.attempts
}

pty:kill is a separate implementation from killPtyFromRuntimeController and
is the one an ordinary tab close reaches, so the record was never written on
the path #12447 describes. Extracted it out of inspect.ts (which was over the
line budget and was not what the file is named for) and wired both branches.

Also:
- finishPtyShutdown no longer retires the order. It runs on paths that asked
  the host and on paths that never did, so retiring there was a contract every
  caller had to know, and the one that forgot silently dropped a kill order.
  Retirement is the replay's, on inventory evidence only.
- A recycled relay id now expires its lease. Declining to kill was only half:
  reattach fences on paneKey/tabId, never incarnation, so an untouched lease
  bound the user's old pane to whatever now holds the id.
- Dropped isPtyAlreadyGoneError from the tombstone path. It matches message
  text a transport failure could wear; every tombstone now traces to a listing.
- TTL is owned by a durable prune that actually deletes, not by a branch that
  was unreachable behind the read filter and only looked tested.
- The replay re-reads the inventory per wave and re-checks the fence next to
  each shutdown, and can never reject into the connect path.
@nwparker
nwparker merged commit 7bbb8ad into main Aug 28, 2026
52 of 55 checks passed
brennanb2025 added a commit that referenced this pull request Aug 28, 2026
Resolve inspect.ts: #17011 moved pty:kill into renderer-kill.ts, which keeps
its inline barrier await. The swap-window helper and both gates stay.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
…stablyai#12447 item 1) (stablyai#17011)

* fix(ssh): replay an undelivered remote PTY stop on the next handshake

A pty.shutdown that dies on the transport left the remote shell running
forever: kill.ts marked liveness unverifiable and nothing retried.

Record the undelivered stop on the existing durable SshRemotePtyLease and
replay it against the authoritative host on the next handshake to that same
target, fenced by the host-minted PTY incarnation so a replay cannot kill a
later PTY that reused a recycled pty-N id. Retire the record on confirmed
delivery, on the host reporting the PTY absent, and on a bounded TTL.

No wire change: the fence reads incarnationId, already published on
pty.listProcesses. A host that does not publish it degrades to no replay.

* fix(ssh): do not leave a replayable kill order behind a reversible stop

Worktree sleep stops through stopAndWait and marks those stops reversible;
when one does not land the pane stays live and the user keeps using it. An
order recorded there would come back on a later handshake and kill that
terminal. Only killPtyFromRuntimeController — where the client gives the PTY
up for good — records one, and it skips any PTY a reversible stop owns.

* fix(ssh): cover the renderer kill route and harden the replay's evidence

pty:kill is a separate implementation from killPtyFromRuntimeController and
is the one an ordinary tab close reaches, so the record was never written on
the path stablyai#12447 describes. Extracted it out of inspect.ts (which was over the
line budget and was not what the file is named for) and wired both branches.

Also:
- finishPtyShutdown no longer retires the order. It runs on paths that asked
  the host and on paths that never did, so retiring there was a contract every
  caller had to know, and the one that forgot silently dropped a kill order.
  Retirement is the replay's, on inventory evidence only.
- A recycled relay id now expires its lease. Declining to kill was only half:
  reattach fences on paneKey/tabId, never incarnation, so an untouched lease
  bound the user's old pane to whatever now holds the id.
- Dropped isPtyAlreadyGoneError from the tombstone path. It matches message
  text a transport failure could wear; every tombstone now traces to a listing.
- TTL is owned by a durable prune that actually deletes, not by a branch that
  was unreachable behind the read filter and only looked tested.
- The replay re-reads the inventory per wave and re-checks the fence next to
  each shutdown, and can never reject into the connect path.

(cherry picked from commit 7bbb8ad)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…stablyai#12447 item 1) (stablyai#17011)

* fix(ssh): replay an undelivered remote PTY stop on the next handshake

A pty.shutdown that dies on the transport left the remote shell running
forever: kill.ts marked liveness unverifiable and nothing retried.

Record the undelivered stop on the existing durable SshRemotePtyLease and
replay it against the authoritative host on the next handshake to that same
target, fenced by the host-minted PTY incarnation so a replay cannot kill a
later PTY that reused a recycled pty-N id. Retire the record on confirmed
delivery, on the host reporting the PTY absent, and on a bounded TTL.

No wire change: the fence reads incarnationId, already published on
pty.listProcesses. A host that does not publish it degrades to no replay.

* fix(ssh): do not leave a replayable kill order behind a reversible stop

Worktree sleep stops through stopAndWait and marks those stops reversible;
when one does not land the pane stays live and the user keeps using it. An
order recorded there would come back on a later handshake and kill that
terminal. Only killPtyFromRuntimeController — where the client gives the PTY
up for good — records one, and it skips any PTY a reversible stop owns.

* fix(ssh): cover the renderer kill route and harden the replay's evidence

pty:kill is a separate implementation from killPtyFromRuntimeController and
is the one an ordinary tab close reaches, so the record was never written on
the path stablyai#12447 describes. Extracted it out of inspect.ts (which was over the
line budget and was not what the file is named for) and wired both branches.

Also:
- finishPtyShutdown no longer retires the order. It runs on paths that asked
  the host and on paths that never did, so retiring there was a contract every
  caller had to know, and the one that forgot silently dropped a kill order.
  Retirement is the replay's, on inventory evidence only.
- A recycled relay id now expires its lease. Declining to kill was only half:
  reattach fences on paneKey/tabId, never incarnation, so an untouched lease
  bound the user's old pane to whatever now holds the id.
- Dropped isPtyAlreadyGoneError from the tombstone path. It matches message
  text a transport failure could wear; every tombstone now traces to a listing.
- TTL is owned by a durable prune that actually deletes, not by a branch that
  was unreachable behind the read filter and only looked tested.
- The replay re-reads the inventory per wave and re-checks the fence next to
  each shutdown, and can never reject into the connect path.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant